package com.btcode.netty.server.session;

import com.btcode.netty.server.session.util.ChannelUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import java.util.Date;

public class IoSession {

    private Channel channel;
    private String userId;
    private String ip;
    private long lastTime;

    public IoSession(Channel channel) {
        this.channel = channel;
        this.ip = ChannelUtil.getIp(channel);
        this.lastTime = System.currentTimeMillis();
    }

    public boolean sendMsg(byte[] msg) {
        if (channel != null && channel.isActive() && channel.isWritable()) {
            //不用ByteBuf包装可能无法发送处处，没有设置默认的encoder，采用通用模式
//            ByteBuf byteBuf = ByteBufUtil.writeUtf8(PooledByteBufAllocator.DEFAULT, new String(msg));
//            ByteBuf byteBuf = Unpooled.copiedBuffer(msg);

            ByteBuf byteBuf = channel.alloc().buffer(msg.length);
            byteBuf.writeBytes(msg);

            channel.writeAndFlush(byteBuf);
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return String.format("userId:%s, ip:%s, lastConTime:%s", userId, ip, new Date(lastTime));
    }

    public boolean isClose() {
        return channel == null || !channel.isActive() || !channel.isOpen();
    }

    public void close() {
        try {
            if (this.channel == null) {
                return;
            }
            channel.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public long getLastTime() {
        return lastTime;
    }

    public void setLastTime(long lastTime) {
        this.lastTime = lastTime;
    }
}